//
//  EditOwnerInfoForCommertialView.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/6/1.
//

import UIKit
import RxSwift
import RxCocoa
import RxGesture
import AMPopTip
import SnapKit
class EditOwnerInfoForCommertialView: View {
    private lazy var disposeBag = DisposeBag()
    @objc dynamic var viewModel: EditOwnerInfomationViewModel!
    
    let companyABNView = TextFieldWithRequiredView(.abn)
    let companyNameView = TextFieldWithRequiredView()
    let gstSwitchBtn = SwitchButton()
    let positionView = TextFieldWithRequiredView()
    let mobileView = TextFieldWithRequiredView(.phone)
    let emailView = TextFieldWithRequiredView(.email)
    let ownerSTCUnitPriceView = TextFieldWithRequiredView(.unitPrice)
    let companyRepresentativeNameView = TextFieldWithRequiredView()
    
    override func setUpView() {
        //2.Company ABN title
        let companyABNTitle = LabelWithRedStarView(R.string.localizable.companyABN())
        self.addSubview(companyABNTitle)
        companyABNTitle.snp.makeConstraints { (make) in
            make.top.left.equalToSuperview()
            make.height.width.greaterThanOrEqualTo(0)
        }
        //2.1.Company ABN text
        self.addSubview(companyABNView)
        companyABNView.snp.makeConstraints { (make) in
            make.top.equalTo(companyABNTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.equalTo(companyABNTitle)
            make.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
        }
        //3.Company Name title
        let companyNameTitle = LabelWithRedStarView(R.string.localizable.companyName())
        self.addSubview(companyNameTitle)
        companyNameTitle.snp.makeConstraints { (make) in
            make.top.equalTo(companyABNView.snp.bottom).offset(Constant.TopBottomMargin)
            make.left.equalTo(companyABNTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //3.1.Company Name text
        self.addSubview(companyNameView)
        companyNameView.snp.makeConstraints { (make) in
            make.top.equalTo(companyNameTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.right.equalTo(companyABNView)
            make.height.greaterThanOrEqualTo(0)
        }
        //gst
        let gstTitle = ContentLabel(text: R.string.localizable.gsT())
        self.addSubview(gstTitle)
        gstTitle.snp.makeConstraints { (make) in
            make.top.equalTo(companyNameView.snp.bottom).offset(Constant.TopBottomMargin)
            make.left.equalTo(companyABNView)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //
        self.addSubview(gstSwitchBtn)
        gstSwitchBtn.snp.makeConstraints { (make) in
            make.centerY.equalTo(gstTitle)
            make.right.equalTo(-Constant.LeftRightMargin)
            make.size.equalTo(SwitchButton.size)
        }
        //5.companyRepresentativeName title
        let companyRepresentativeNameTitle = LabelWithRedStarView(R.string.localizable.companyRepresentativeFullName())
        self.addSubview(companyRepresentativeNameTitle)
        companyRepresentativeNameTitle.snp.makeConstraints { (make) in
            make.top.equalTo(gstSwitchBtn.snp.bottom).offset(Constant.TopBottomMargin)
            make.left.equalTo(companyABNView)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //5.1.Company Name text
        self.addSubview(companyRepresentativeNameView)
        companyRepresentativeNameView.snp.makeConstraints { (make) in
            make.top.equalTo(companyRepresentativeNameTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.right.equalTo(companyABNView)
            make.height.greaterThanOrEqualTo(0)
        }
        //position
        let positionTitle = LabelWithRedStarView(R.string.localizable.position())
        self.addSubview(positionTitle)
        positionTitle.snp.makeConstraints { (make) in
            make.top.equalTo(companyRepresentativeNameView.snp.bottom).offset(Constant.TopBottomMargin)
            make.left.equalTo(companyABNView)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //6.1.mobile textfield
        self.addSubview(positionView)
        positionView.snp.makeConstraints { (make) in
            make.top.equalTo(positionTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.right.equalTo(companyNameView)
            make.height.greaterThanOrEqualTo(0)
        }
        //6.mobile
        let mobileTitle = LabelWithRedStarView(R.string.localizable.mobile())
        self.addSubview(mobileTitle)
        mobileTitle.snp.makeConstraints { (make) in
            make.top.equalTo(positionView.snp.bottom).offset(Constant.TopBottomMargin)
            make.left.equalTo(companyABNView)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //6.1.mobile textfield
        self.addSubview(mobileView)
        mobileView.snp.makeConstraints { (make) in
            make.top.equalTo(mobileTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.right.equalTo(companyNameView)
            make.height.greaterThanOrEqualTo(0)
        }
        //7.Email
        let emailTitle = LabelWithRedStarView(R.string.localizable.email())
        self.addSubview(emailTitle)
        emailTitle.snp.makeConstraints { (make) in
            make.top.equalTo(mobileView.snp.bottom).offset(Constant.TopBottomMargin)
            make.left.equalTo(companyABNView)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //7.1.Email textfield
        self.addSubview(emailView)
        emailView.snp.makeConstraints { (make) in
            make.top.equalTo(emailTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.right.equalTo(companyNameView)
            make.height.greaterThanOrEqualTo(0)
            
        }
        //3.Owner’s STC Unit Price
        let ownerSTCUnitPriceTitle = LabelWithRedStarView(R.string.localizable.ownerSSTCUnitPrice())
        self.addSubview(ownerSTCUnitPriceTitle)
        ownerSTCUnitPriceTitle.snp.makeConstraints { (make) in
            make.top.equalTo(emailView.snp.bottom).offset(Constant.TopBottomMargin)
            make.left.equalTo(companyNameView)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //tip btn
        let ownerSTCUnitPriceTipBtn = UIButton()
        ownerSTCUnitPriceTipBtn.setImage(R.image.installation_detail_spv_tip_icon(), for: UIControl.State.normal)
        self.addSubview(ownerSTCUnitPriceTipBtn)
        ownerSTCUnitPriceTipBtn.snp.makeConstraints { (make) in
            make.centerY.equalTo(ownerSTCUnitPriceTitle)
            make.left.equalTo(ownerSTCUnitPriceTitle.snp.right)
            make.height.width.equalTo(40)
        }
        
        //3.1.Additional Information textfield
        ownerSTCUnitPriceView.textField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 25, height: 0))
        self.addSubview(ownerSTCUnitPriceView)
        ownerSTCUnitPriceView.snp.makeConstraints { (make) in
            make.top.equalTo(ownerSTCUnitPriceTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.right.equalTo(companyNameView)
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalTo(-Constant.TopBottomMargin)
        }
        //输入框前边显示$符号
        let moneyImageLabel = ContentLabel(R.font.interRegular(size: 15),hexStr: Constant.TextFieldColorHexStr)
        moneyImageLabel.text = "$"
        ownerSTCUnitPriceView.addSubview(moneyImageLabel)
        moneyImageLabel.snp.makeConstraints { make in
            make.left.equalTo(ownerSTCUnitPriceView.textField).offset(10)
            make.width.height.greaterThanOrEqualTo(0)
            make.centerY.equalTo(ownerSTCUnitPriceView.textField)
        }
        //unit price tip btn
        ownerSTCUnitPriceTipBtn.rx.tap.subscribe { [weak self] (data)in
            guard let strongSelf = self else {return }
            PopViewUtil.shared.showPopView(R.string.localizable.thisIsTheSTCPriceOfferedToYourCustomerARecipientCreatedTaxInvoiceWillBeIssuedToYourCustomerViaEmailAndTextMessageWhenJobBecomesSubmitted(),tipBtn: ownerSTCUnitPriceTipBtn, position: .up, contentView: strongSelf)
        }.disposed(by: self.disposeBag)
        self.initBiding()
    }
    func setData(_ viewModel: EditOwnerInfomationViewModel){
        self.viewModel = viewModel
        self.gstSwitchBtn.switchOn(self.viewModel.gst)
        self.companyNameView.textField.text = self.viewModel.company_name
        self.companyRepresentativeNameView.textField.text = self.viewModel.owner_representative_name
        self.positionView.textField.text = self.viewModel.owner_representative_position
        self.companyABNView.textField.text = self.viewModel.home_owner_abn
        self.ownerSTCUnitPriceView.textField.text = self.viewModel.price_to_the_home_owner
        self.mobileView.textField.text = self.viewModel.mobile
        self.emailView.textField.text = self.viewModel.email
    }
    //MARK: - 打开编辑时，检验必填项及有效信息
    func validateAllRequiredFieldWhenEdit(){
        self.emailView.checkIfStandardValid()
        self.mobileView.checkIfStandardValid()
        //abn提交的时候会调用API校验，此处不用校验
        self.companyABNView.checkIfStandardValid()
        if self.companyABNView.validStatus.value == .valid{
            self.checkABN(self.viewModel.home_owner_abn) { _ , errMsg in
                if errMsg != ""{
                    self.companyABNView.showInvalidMsg(errMsg)
                }
            }
        }
        self.companyNameView.checkIfStandardValid()
        self.companyRepresentativeNameView.checkIfStandardValid()
        self.positionView.checkIfStandardValid()
        self.ownerSTCUnitPriceView.checkIfStandardValid()
        
    }
    //MARK: - 数据绑定
    private func initBiding(){
        //监听company name编辑内容
        companyNameView.editingDidEndClosure = {[weak self] (data)in
            guard let strongSelf = self else {return }
            strongSelf.viewModel.company_name = data
        }
        //监听companyRepresentativeName内容
        companyRepresentativeNameView.editingDidEndClosure = {[weak self] (data)in
            guard let strongSelf = self else {return }
            strongSelf.viewModel.owner_representative_name = data
        }
        //监听position内容
        positionView.editingDidEndClosure = {[weak self] (data)in
            guard let strongSelf = self else {return }
            strongSelf.viewModel.owner_representative_position = data
        }
        //监听mobile内容
        mobileView.editingDidEndClosure = {[weak self] (data)in
            guard let strongSelf = self else {return }
            strongSelf.viewModel.mobile = data
        }
        //监听email内容
        emailView.editingDidEndClosure = {[weak self] (data)in
            guard let strongSelf = self else {return }
            strongSelf.viewModel.email = data
        }
        //监听ownerSTCUnitPrice内容
        ownerSTCUnitPriceView.editingDidEndClosure = {[weak self] (content)in
            guard let strongSelf = self else {return }
            var realContent = content
            if content == "." {
                realContent = "0"
            }else if let doubleValue = Double(realContent) {
                if doubleValue == 0{
                    realContent = "0"
                }else{
                    realContent = "\(doubleValue)"
                }
            }
            strongSelf.ownerSTCUnitPriceView.textField.text = realContent
            strongSelf.viewModel.price_to_the_home_owner = realContent
        }
        //监听abn编辑内容
        companyABNView.editingDidEndClosure = {[weak self] (data) in
            guard let strongSelf = self else {return }
            strongSelf.viewModel.home_owner_abn = data
            strongSelf.toCheckABN()
        }
        //切换gst
        gstSwitchBtn.rx.observe(Int.self, "tag").subscribe {[weak self] (btnTag) in
            guard let strongSelf = self, let tag = btnTag, let _ = strongSelf.viewModel else {return }
            if tag == 1{//开启pick up required
                strongSelf.viewModel.gst = true
            }else{//关闭
                strongSelf.viewModel.gst = false
            }
        }.disposed(by: self.disposeBag)
    }
    
    //MARK: - 处理GST的默认值（create job初始化，或改变property type，或改变owner type,或改变ABN）
    func dealGSTValueByPropertyType(gstFlag: Bool){
        guard let _ = self.viewModel else {return}
        self.viewModel.gst = gstFlag
        self.gstSwitchBtn.switchOn(self.viewModel.gst)
    }
    func dealGSTValueByABN(){
        guard let _ = self.viewModel else {return}
        if self.viewModel.property_type != .residential && self.viewModel.owner_type != .individual{
            self.viewModel.gst = self.viewModel.commercial_gst
            self.gstSwitchBtn.switchOn(self.viewModel.gst)
        }
    }
    //MARK: - 根据ABN的变化设置company name 信息
    private func setCompanyName(_ name: String){
        self.companyNameView.textField.text = name
        self.viewModel.company_name = name
        if name.count > 0 {
            self.companyNameView.hideInvalidMsg()
        }
    }
    //MARK: - 去检查abn
    func toCheckABN(){
        self.checkABN(self.viewModel.home_owner_abn) { [weak self] companyName, errMsg in
            guard let strongSelf = self else {return }
            strongSelf.setCompanyName(companyName)
            if companyName != ""{
                strongSelf.dealGSTValueByABN()
            }
            if errMsg.count > 0 {
                strongSelf.companyABNView.showInvalidMsg(errMsg)
            }
        }
    }
    //MARK: - 根据abn获取company name
    private func checkABN(_ abn: String, closure: ((String,String)->Void)? = nil){
        //设置被观察属性为false
        if abn.count == 0 {
            self.viewModel.home_owner_abn_valid_flag = false
            self.viewModel.commercial_gst = false
            closure?("","")
            return
        }
        let vm = EditJobInfoService()
        vm.setBlockAfterNetwork { [weak self](result , _) in
            guard let strongSelf = self else {return}
            var abnCompanyName: String = ""
            var checkError: String = ""
            if let dic = result as? NSDictionary, let companyName = dic.object(forKey: "name") as? String, let commercialGSTFlag = dic.object(forKey: "commercial_gst") as? Bool{
                strongSelf.viewModel.home_owner_abn_valid_flag = true
                strongSelf.viewModel.commercial_gst = commercialGSTFlag
                abnCompanyName = companyName
            }else{
                strongSelf.viewModel.home_owner_abn_valid_flag = false
                strongSelf.viewModel.commercial_gst = false
                checkError = R.string.localizable.pleaseEnterValidABN()
            }
            closure?(abnCompanyName,checkError)
            
        } errorBlock: { (code, error) in
            closure?("",error)
        }
        vm.getCompanyNameByABN(abn)
    }
}
